package com.risk.kernel.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: Liwen
 * @createTime: 2025/1/27
 * @description:
 */
@Slf4j
public class MongoUtil {

    public static MongoClient mongoClient = null;
    public static MongoCollection collection = null;

    /**
     * 获取mongo client
     *
     * @return
     */
    public static MongoClient getMongoClient(String host, String port, String userName, String password, String bdSource) {
        if (mongoClient == null) {
            try {
                //ServerAddress()两个参数分别为 服务器地址 和 端口
                ServerAddress serverAddress = new ServerAddress(host, Integer.parseInt(port));
                List addrList = new ArrayList();
                addrList.add(serverAddress);
                //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
                MongoCredential credential = MongoCredential.createScramSha1Credential(userName, bdSource, password.toCharArray());
                List credentials = new ArrayList();
                credentials.add(credential);
                //通过连接认证获取MongoDB连接
                mongoClient = new MongoClient(addrList, credentials);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mongoClient;
    }

    /**
     * 获取指定的collection对象
     *
     * @param dbName
     * @param collName
     * @return
     */
    public static MongoCollection getCollection(String host, String port, String userName, String password, String bdSource, String dbName, String collName) {
        getMongoClient(host, port, userName, password, bdSource);
        if (StringUtils.isEmpty(dbName) || StringUtils.isEmpty(collName)) {
            return null;
        }
        collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

    /**
     * 关闭mogo
     */
    public static void closeMongoClient() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }

    /**
     * 条件精确删除
     *
     * @param dbName
     * @param collName
     * @param bson
     */
    public static void deleteFromMongo(String dbName, String collName, Bson bson) {
        collection.deleteMany(bson);
    }

    /**
     * 条件 模糊删除
     *
     * @param dbName
     * @param collName
     */
    public static void deleteLikeFromMongo(String dbName, String collName, String key, String value) {
        Document match = new Document();
        match.append(key, new Document("$regex", value));
        collection.deleteMany(match);
        log.info("【模糊删除成功】=================================================");
    }


    /**
     * 查询document
     *
     * @param dbName
     * @param collName
     * @return
     */
    public static List<String> findDocument(String dbName, String collName, String key, String value) {
        Document match = new Document();
        match.append(key, new Document("$regex", value));
        String resultDoc = "";
        List<String> list = new ArrayList<>();
        MongoCursor iterator = collection.find(match).iterator();
        while (iterator.hasNext()) {
            Document document = (Document) iterator.next();
//            log.info("【查询文档成功】" + JSON.toJSONString(resultDoc));
            list.add(JSON.toJSONString(document));
        }

        return list;
    }

    /**
     * 根据多条件查询，返回一个字段
     *
     * @param queryMap: 查询条件
     * @param queryKey  返回指定字段
     */
    public static String queryOne(String dbName, String collName, Map<String, String> queryMap, String queryKey) {
        String value = "";
        BasicDBObject queryKeys = new BasicDBObject();
        for (String key : queryMap.keySet()) {
            queryKeys.put(key, queryMap.get(key));
            log.info("查询条件：" + key + ":" + queryMap.get(key));
        }
        MongoCursor iterator = collection.find(queryKeys).iterator();
        while (iterator.hasNext()) {
            Document document = (Document) iterator.next();
            String jsonString = JSON.toJSONString(document);
            value = JSONPath.eval(jsonString, "$" + queryKey) + "";
        }
        return value;
    }

    public static void insert(String dbName, String collName, String jsonString) {
        collection.insertOne(Document.parse(jsonString));
    }

}
